Load a Run
Once you have found the latest episode, load the latest run the user has participated in.
Load the run
The runs in the template application are scoped to an episode.
- To find the latest run for the user, call the
runAdapter.query()function with a user-specific scope in thesearchOptionsparameter. - If the user hasn't participated in this simulation yet, create a run.
Getting the latest run for the user
// Define the user-specific scope.
const scope = {
scopeBoundary: SCOPE_BOUNDARY.EPISODE,
scopeKey: episodeKey,
userKey: session.userKey,
};
// Call the run adapter function.
const [run] = await runAdapter
.query(MODEL, {
scope,
filter: ['run.hidden=false'],
sort: ['-run.created'],
max: 1,
})
.then((response) => response.values as Array<RunReadOutView>);
// Returns the user's most recent model run.
if (run) return run;
// Otherwise, create a run.
return runAdapter.create(MODEL, scope).then((run) => run as RunReadOutView);
Load the variables
Variables represent the state of the run. To allow the user to continue where they left off, load the run variables.
The metadata of the variables that comprise the run state can be stored in a special context file. For simplicity, in the template application, the variable names are declared as a constant array.
Call the runAdapter.getVariables() function with these parameters.
- The run key for the user's most recent run.
- The array of variable names.
- A value from the
RITUALenum.
Loading the variables for the user's most recent run
// Define the variable names
const RANGES = [
'Time',
'Bike_Sales',
'Price',
'Revenue',
'Variable_Costs',
'Fixed_Costs',
'Total_Costs',
'Profit',
'Step',
] as const;
// Load the run variables
runAdapter.getVariables(runKey!, [...RANGES], { ritual: 'REVIVE' })
.then((response) => {
invariant(
!Array.isArray(response),
'Fetched multiple runs when only one was expected.'
);
return response;
})